package com.jsh.erp.interceptor;

import com.jsh.erp.session.UserSessionManager;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = LoggerFactory.getLogger(UserInterceptor.class);

	@Resource
	UserSessionManager sessionManager;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (!(handler instanceof HandlerMethod)) {
			//return true;
		}

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");


		Object userInfo = sessionManager.getSessionUserWithCache();

		if(userInfo!=null){
			//已登录
			return true;
		}else{
			//访问的url
			String url = request.getRequestURL().toString();
			//未登录
			//注册的访问放行，其它访问跳转到登录界面
			if(url.contains("/register.html")){
				return true;
			}else{
				response.sendRedirect("/login.html");
			}
		}
		return false;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}


}
